package com.iwdnb.gkgz;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Objects;
import java.util.UUID;

import javax.swing.*;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.BrowserContextParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import gui.ava.html.Html2Image;
import gui.ava.html.renderer.ImageRenderer;

public class JxBrowserDemo {
    private static Browser browser;

        public static void main(String[] args) throws InterruptedException {
            stockEmotionSaveImage("2025-01-07");
        }

        private static void init() {
            jbcrack.Cracker.justDoIt();
            String identity = UUID.randomUUID().toString();
            BrowserContextParams params = new BrowserContextParams("temp/browser/" + identity);
            BrowserContext context1 = new BrowserContext(params);
            browser = new Browser(context1);
            BrowserView view = new BrowserView(browser);
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.add(view, BorderLayout.CENTER);
            frame.setSize(1000, 800);
            frame.setLocationRelativeTo(null);
            frame.setVisible(false);
        }

        // 执行方法
        public static void stockEmotionSaveImage(String date) {
            if (Objects.isNull(browser)) {
                init();
            }
            browser.loadURL("http://root.com:8001/api/stock/chart/stockEmotionSaveImage?date=" + date);
        }

    /**
     * 根据HTML内容转Image
     *
     * @param htmText HTML文本字符串
     */
    public static BufferedImage htmlConvertImg(String htmText) {
        //最终返回的byte流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Html2Image html2Image = Html2Image.fromHtml(htmText);
        ImageRenderer imageRenderer = html2Image.getImageRenderer();
        BufferedImage image = imageRenderer.getBufferedImage(BufferedImage.TYPE_INT_RGB);
        return image;
        //ImageIO.write(grayPicture, formatType, byteArrayOutputStream);
        //return byteArrayOutputStream.toByteArray();
    }
}
